package web.myBook.controllers;

import java.io.IOException;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Event;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.ProcessEvent;
import javax.portlet.RenderRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.EventMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.PortletDisplay;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletURLFactoryUtil;
import com.myBook.slayer.model.MyBook;
import com.myBook.slayer.model.impl.MyBookImpl;
import com.myBook.slayer.service.MyBookLocalServiceUtil;


@Controller
@RequestMapping("VIEW")
public class MyBookController {
	
	@Autowired
	private MyBook myBook;
	
	@Autowired
	private BookValidator bookValidator;
	
	public MyBook getMyBook() {
		return myBook;
	}

	public void setMyBook(MyBook myBook) {
		this.myBook = myBook;
	}

	
	public BookValidator getBookValidator() {
		return bookValidator;
	}

	public void setBookValidator(BookValidator bookValidator) {
		this.bookValidator = bookValidator;
	}
	

	@RenderMapping
	public String handleRenderRequest(Model model, RenderRequest renderRequest){
		 //Used for the initial form as well as for redisplaying with errors.
		ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
		PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
		
		System.out.println("help mode enabled :: " + portletDisplay.isShowHelpIcon());
		portletDisplay.setShowHelpIcon(true);
		
		return "view";
	}
	
	
	@RenderMapping(params ="action=list")
	public String handleRenderRequest2(PortletDisplay portletDisplay){
		portletDisplay.setShowHelpIcon(true);
		return "list";
	}
	
	@RenderMapping(params ="action=insert")
	public String handleRenderRequest3(Model model){
		 if (!model.containsAttribute("book")) {
	            model.addAttribute("book", myBook);
	        }
		return "insert";
	}

	@RenderMapping(params ="action=showUpdateForm")
	public String showUpdateForm(Model model, RenderRequest renderRequest) throws PortalException, SystemException{
		long bookId = ParamUtil.getLong(renderRequest, "id");
		MyBook book = MyBookLocalServiceUtil.getMyBook(bookId);
        model.addAttribute("book", book);
		return "insert";
	}

	
	@ActionMapping
	protected void addBook(@ModelAttribute("book") MyBookImpl command, BindingResult result,
            SessionStatus status, ActionResponse response,ActionRequest actionRequest)
			throws Exception {
		
		bookValidator.validate(command, result);
		if (result.hasErrors()) {
			System.out.println(command.toString());
			status.setComplete();
			}
		else{
			MyBookLocalServiceUtil.addMyBook(command);
			
			ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
			//themeDisplay.getPortletDisplay()
			//String portletName = ParamUtil.getString(actionRequest,"rootPortletId");
			String portletName = (String) actionRequest.getAttribute(WebKeys.PORTLET_ID);
			PortletURL successPageURL = 
				PortletURLFactoryUtil.create(
				actionRequest, 
				portletName, 
				themeDisplay.getPlid(),
				PortletRequest.RENDER_PHASE);
			successPageURL.setParameter("action", "list");
			response.sendRedirect(successPageURL.toString());
		}
		
		

	}
	
	@ActionMapping(params = "action=updateBook" )
	protected void updateBook(@ModelAttribute("book") MyBookImpl command, 
           ActionResponse response,ActionRequest actionRequest)
			throws Exception {
		ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
		MyBookLocalServiceUtil.updateMyBook(command);
		response.sendRedirect(PortalUtil.getLayoutURL(themeDisplay));
	}
	
	@ActionMapping(params = "action=deleteBook" )
	public void deleteBook(@RequestParam("id") long bookId ){
		try {
			 if (bookId > 0L) {
			MyBookLocalServiceUtil.deleteMyBook(bookId);
			 }
		} catch (PortalException e) {
			e.printStackTrace();
		} catch (SystemException e) {
			e.printStackTrace();
		}
	}
	

	@EventMapping
	public void quickAdd(EventRequest request, EventResponse response)
			throws PortletException, IOException {

		Event event = request.getEvent();
		
		MyBook myBook = (MyBook) event.getValue();
		
		try {
			MyBookLocalServiceUtil.addMyBook(myBook);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}


	@ActionMapping(params="action=searchBook")
	public void searchBook(@RequestParam("searchTerm") String searchTerm, 
	           ActionResponse response,ActionRequest request) throws Exception {
		
		//String searchTerm = ParamUtil.getString(actionRequest, "searchTerm");
		
		try {
			List<MyBook> books = MyBookLocalServiceUtil.search(searchTerm);	
			request.setAttribute("SEARCH_RESULT", books);
			response.setRenderParameter("action", "list");
			
		} catch (SystemException e) {
			
			e.printStackTrace();
		}
	}


}
